<template>
  <div id="table-print">
    <table class="table table-bordered table-sm" v-loading="loading">
      <colgroup>
        <col width="5%" />
        <col width="11%" />
        <col width="10%" />
        <col width="9%" />
        <col width="9%" />
        <col width="9%" />
        <col width="9%" />
        <col width="9%" />
        <col width="9%" />
        <col width="5%" />
        <col width="5%" />
        <col width="5%" />
        <col width="5%" />
      </colgroup>
      <thead class="text-center bg-light font-weight-bold table-vertical-middle">
        <tr>
          <td rowspan="2">序号</td>
          <td rowspan="2">县（区）名称</td>
          <td rowspan="2">该县所属地级市</td>
          <td colspan="2">{{ reportYear }}年新增</td>
          <td colspan="2">121号文以来累计新增</td>
          <td colspan="2">在保</td>
          <td rowspan="2">是否9+3贫困县</td>
          <td rowspan="2">是否考核大县</td>
          <td rowspan="2">是否参考县</td>
          <td rowspan="2">是否覆盖大县</td>
        </tr>
        <tr>
          <td>
            <div>担保金额</div>
            （万元）
          </td>
          <td>项目数</td>
          <td>
            <div>担保金额</div>
            （万元）
          </td>
          <td>项目个数</td>
          <td>
            <div>余额</div>
            （万元）
          </td>
          <td>项目个数</td>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in tableData" :key="index">
          <td class="text-right">{{ index + 1 }}</td>
          <td class="text-center">{{ item.address_code_name }}</td>
          <td class="text-center">{{ item.city_address_code_name }}</td>
          <td class="text-right" data-alignment-horizontal="bottom">
            {{ item.current_year_new_funds_dot }}
          </td>
          <td class="text-right" data-alignment-horizontal="bottom">
            {{ item.current_year_new_total }}
          </td>
          <td class="text-right" data-alignment-horizontal="bottom">{{ item.all_funds_dot }}</td>
          <td class="text-right" data-alignment-horizontal="bottom">{{ item.all_total }}</td>
          <td class="text-right" data-alignment-horizontal="bottom">{{ item.on_gua_funds_dot }}</td>
          <td class="text-right" data-alignment-horizontal="bottom">{{ item.on_gua_total }}</td>
          <td class="text-center">
            <radio-icon :value="item.is_9_3"></radio-icon>
          </td>
          <td class="text-center">
            <radio-icon :value="item.is_assess_county"></radio-icon>
          </td>
          <td class="text-center">
            <radio-icon :value="item.is_refer_county"></radio-icon>
          </td>
          <td class="text-center">
            <radio-icon :value="item.is_bus_assess_county"></radio-icon>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import { addressLevel, excelTableExport, stringFormatDot } from '@vimi/utils-tool'

const formatFunds = v => stringFormatDot(v.toFixed(2))

const fields = [
  'address_code',
  'address_code_name',
  'city_address_code',
  'city_address_code_name',
  'is_9_3',
  'is_assess_county',
  'is_bus_assess_county',
  'is_refer_county',
]
const groupFunc = [
  'all_funds',
  'all_total',
  'current_year_new_funds',
  'current_year_new_total',
  'on_gua_funds',
  'on_gua_total',
]

export default {
  components: {
    'radio-icon': {
      functional: true,
      props: {
        value: {
          type: [String, Number],
          default: '0',
        },
      },
      render: (h, ctx) =>
        +ctx.props.value === 1
          ? h('div', null, [
              h('i', { class: 'el-icon-check' }),
              h('div', { style: 'opacity:0;width:0;height:0;overflow:hidden;' }, '是'),
            ])
          : h(''),
    },
  },
  props: {
    addressCode: String,
    areaType: {
      type: String,
      default: 'is_9_3',
    },
    queryDate: Date,
  },
  data() {
    return {
      loading: false,
      downloadLoading: false,

      params: {
        isBIQuery: 1,
        groupFields: '',
        groupFunc: '',
        fields: [],
        'load_end_date_ny.eq': '',
      },
      order: {
        N1city_address_code: 'asc',
        N1address_code: 'asc',
      },
      tableName: 'report_analysis_coverage_view',
      tableData: [],
      allData: [],
      allAreaData: [],
    }
  },
  computed: {
    reportYear() {
      return this.$utils.dateFormat(this.queryDate || new Date(), 'yyyy')
    },
  },
  watch: {},
  created() {
    this.$watch('addressCode', function () {
      this.handleQuery()
    })
    this.$watch('areaType', function () {
      this.handleQuery()
    })
    this.$watch('queryDate', function () {
      this.handleDateQuery()
    })

    this.params.groupFunc = groupFunc
      .reduce((p, c) => {
        p.push(`sum(${c})`)
        return p
      }, [])
      .join(',')
    this.params.groupFields = fields.join(',')
    this.params.fields = fields

    this.setDateParams()
    this.getData()
  },
  mounted() {},
  methods: {
    setDateParams(date = new Date()) {
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      this.params['load_end_date_ny.gt'] = `${year}01`
      this.params['load_end_date_ny.lte'] = year + `${month}`.padStart(2, '0')
    },

    async getData() {
      this.loading = true
      Promise.all([this.getCountData(), this.getAllAreaData()])
        .then(([res1, res2]) => {
          const allData = []
          for (const d of res2) {
            const index = res1.findIndex(it => it.address_code === d.address_code)
            if (index > -1) {
              allData.push({
                ...d,
                ...res1[index],
              })
              res1.splice(index, 1)
            } else {
              allData.push({
                ...d,
                all_funds_dot: '0.00',
                current_year_new_funds_dot: '0.00',
                on_gua_funds_dot: '0.00',
                on_gua_total: 0,
                all_total: 0,
                current_year_new_total: 0,
              })
            }
          }

          this.allData = allData
          this.tableData = allData
          this.allAreaData = res2
          this.handleQuery()
          this.$emit('getData', allData)
        })
        .finally(() => {
          this.loading = false
        })
    },

    /**
     * 获取当前选择时间区间的统计数
     */
    getCountData() {
      return this.$api
        .getData(this.$serviceName, this.tableName, this.params, this.order)
        .then(res => {
          const data = res.data || []
          for (const d of data) {
            // 统计字段映射
            groupFunc.forEach((key, index) => {
              d[key] = +d[`p${index || ''}`]
            })

            // 处理金额格式：加逗号、保留两位小数点
            d.all_funds_dot = formatFunds(d.all_total)
            d.current_year_new_funds_dot = formatFunds(d.current_year_new_funds)
            d.on_gua_funds_dot = formatFunds(d.on_gua_funds)
          }
          return data
        })
    },

    /**
     * 获取所有区域（需要显示所有区域），与统计数据的区域匹配
     */
    getAllAreaData() {
      // 缓存
      if (this.allAreaData.length) {
        return Promise.resolve(this.allAreaData)
      }

      return this.$api
        .getData(
          this.$serviceName,
          'address_poverty_related',
          {
            'address_code.endlike': '52',
            groupFields: 'address_code',
          },
          {
            city_address_code: 'asc',
            address_code: 'asc',
          }
        )
        .then(res => res.data || [])
    },

    handleQuery() {
      const { addressCode, areaType } = this
      const al = addressLevel(addressCode)
      const hasSelectArea = !!areaType

      this.tableData = this.allData.filter(it => {
        return (
          (addressCode && al > 0
            ? it.address_code === addressCode || it.city_address_code === addressCode
            : true) && (hasSelectArea ? +it[areaType] === 1 : true)
        )
      })
    },

    handleDateQuery() {
      this.setDateParams(this.queryDate || new Date())
      this.getData()
    },

    onExportExcel() {
      const borderAllThin = {
        left: { style: 'thin' },
        top: { style: 'thin' },
        right: { style: 'thin' },
        bottom: { style: 'thin' },
      }
      const cellStyles = {}
      for (let i = 0; i < 13; i++) {
        cellStyles[`0-${i}`] = { font: { bold: true }, border: borderAllThin }
        cellStyles[`1-${i}`] = { font: { bold: true }, border: borderAllThin }
      }

      this.downloadLoading = true
      excelTableExport('table-print', '导出', {
        styles: {
          border: borderAllThin,
          alignment: {
            vertical: 'center',
            horizontal: 'center',
            wrapText: true,
          },
        },
        cellStyles,
      }).finally(() => {
        this.downloadLoading = false
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
